#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
  ui->setupUi(this);
  this->setWindowTitle("TCP客户端");
  connect(&thread, &WorkThread::showMessage, this, &Widget::showMessage);
}

Widget::~Widget() {
  thread.stopThread();
  thread.wait();
  delete ui;
}

void Widget::on_btnConnect_clicked() {
  if (!m_connected) {
    // 获取IP与端口
    QString ip = ui->lineEditIP->text();
    uint port = ui->lineEditPort->text().toUInt();

    // 3 启动线程
    thread.startThread(ip, port);

  } else {
    // 断开与服务器的连接
    thread.stopThread();
  }
}

void Widget::showMessage(const QString &info, bool conn) {
  ui->messageShoxEdit->appendPlainText(info);
  m_connected = conn;
  if (conn) {
    ui->btnConnect->setText("断开");
  } else {
    ui->btnConnect->setText("连接");
  }
}

void Widget::on_btnSend_clicked() {
  QString msg = ui->messageEdit->text();
  QByteArray data = msg.toUtf8();
  thread.send(data);
}
